import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import axios from 'axios';
import { getUser, setUserInfo, updateHouse, getUserByOpenId, select_like, getUserById, updateByOpenid } from './user.service';
import WXBizDataCrypt from './WXBizDataCrypt';
import { SignToken } from './user.service';
import { APPSECRET, WXPAY_APP_ID } from "../app/app.config";
import { createUserAuth, selectUserAuth, userAuthUpdate } from '../user_auth/user_auth.service';
import { redirect_uri } from '../app/constants.js';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let pageNo = request.query.pageNo
  let userId = request.query.userId

  const data = await getUser(10, parseInt(`${pageNo}`, 10), parseInt(`${userId}`));
  
  response.send(data);
}

/**
 * 获取内容(按 openId 查找)
 */
export const userDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { openId } = request.params;

  // 调取内容
  try {
    const data = await getUserByOpenId(parseInt(openId, 10));

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 获取内容(按 openId 查找)
 */
export const userCon = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取用户 ID
  const { userId } = request.body;
  
  try {
    const data = await getUserById(userId);
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 模糊查询
 */
export const selectLike = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取关键词
  const {keyWord} =request.query;

  try {
    const data = await select_like(keyWord as any);
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 微信 H5应用登录
 */
export const getCode = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let _redirect_uri = redirect_uri;
  let code = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WXPAY_APP_ID}&redirect_uri=${encodeURIComponent(_redirect_uri)}&response_type=code&scope=snsapi_userinfo&#wechat_redirect`

  try {
    response.send(code);
  } catch (error) {
    next(error);
  }
}

/**
 * 微信 H5应用登录 获取用户信息
 */
export const getuserInfo = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  const code = request.body.code;
  
  let req_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WXPAY_APP_ID}&secret=${APPSECRET}&code=${code}&grant_type=authorization_code`
  axios.get(req_url).then(async res => {
    const getInfo_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' + res.data.access_token + '&openid=' + res.data.openid +'&lang=zh_CN'
    await axios.get(getInfo_url).then(async res=> {
      const userModal = await res.data
      delete userModal.privilege
      let data: any;

      // 查询该用户是否存在
      const userInfo = await getUserByOpenId(userModal.openid)
      if (userInfo !== undefined) {
        await updateByOpenid(userModal, userModal.openid)
        data = await getUserByOpenId(userModal.openid)
      } else {
        await setUserInfo(userModal);
        data = await getUserByOpenId(userModal.openid);
      }
      delete data.openid

      const payload = { id: data.id };
      // 签发令牌
      const token = SignToken({ payload });
      // 做出响应
      response.send({ data, token });
    })
  }).catch(err => {
    console.log("err: ", err)
  })

  // try {
  //   let data = {};
  //   response.send(data);
  // } catch (error) {
  //   next(error);
  // }
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  const userModal = request.body;

  // 创建内容
  try {
    const data = await setUserInfo(userModal);
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { userId, vipDay } = request.body;

  let newTime = Math.floor(new Date().getTime() / 1); // 获取目前时间 86400000
  let post: any = request.body;
  post.vipAuth_endTime = newTime + vipDay * 86400000;

  // 更新内容
  const postModel = _.pick(post, ['vipAuth_endTime']);

  // 手动开通会员
  // 获取权限

  let startTime = parseInt(`${new Date().getTime() / 1}`, 10);
  let endTime = parseInt(`${startTime + 86400000 * vipDay}`, 10)
  const post_1 = { user_id: userId, vip_days: vipDay, startTime: startTime, endTime: endTime }

  const userData = await selectUserAuth(parseInt(`${userId}`, 10));

  if (userData[0]?.user_id) {
    await userAuthUpdate(parseInt(`${userId}`, 10), post_1);
  } else {
    await createUserAuth(post_1)
  }

  // 更新内容
  try {
    const data = await updateHouse(postModel, parseInt(userId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}


/**
 * 更新头像
 */
export const updateAvatar = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { userId } = request.body;

  const post = { avatarUrl: request.body.avatarUrl }

  // 更新内容
  const postModel = _.pick(post, ['avatarUrl']);

  // 更新内容
  try {
    const data = await updateHouse(postModel as any, parseInt(userId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 用户登录
 */
export const login = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { code, encryptedData, iv } = request.body;
  
  const AppID = WXPAY_APP_ID;
  const AppSecret = APPSECRET;
  const url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + AppID + '&secret=' + AppSecret + '&js_code=' + code +'&grant_type=authorization_code';
  
  try {
    axios.get(url).then(async res => {   
      
      const openId = res.data.openid
      const sessionKey = res.data.session_key;

      var pc = new WXBizDataCrypt(openId, sessionKey)
      var info = pc.decryptData(encryptedData, iv)

      let userInfo = {
        openId: openId,
        nickName: info.nickName,
        gender: info.gender,
        city: info.city,
        avatarUrl: info.avatarUrl
      }
      
      let user = await getUserByOpenId(openId)
      if (user == undefined ) {
        await setUserInfo(userInfo)
        // await getIdHouse(openId)

        user = await getUserByOpenId(openId)
      } else if (openId == user.openId) {
        user = await getUserByOpenId(openId)
        await updateHouse(userInfo, user.id)
        
        delete user.openId
        // delete user.id
        delete user.phoneNum
        delete user.city
        delete user.gender
        delete user.lastLoginTime
        delete user.registrationTime
      }
      const payload = { id: user.id, name: user.name };
      // 签发令牌
      const token = SignToken({ payload });
      // 做出响应
      response.send({ user, token });
    }).catch(error => {
      console.log('error: ', error);
      next()
    })
  } catch (error) {
    next(error);
  }
}

/**
 * 获取用户手机号
 */
export const getPhoneNum = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取 code、encryptedData、iv
  let { code, encryptedData, iv } = request.body;

  const AppID = WXPAY_APP_ID;
  const AppSecret = APPSECRET;
  
  const url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + AppID + '&secret=' + AppSecret + '&js_code=' + code + '&grant_type=authorization_code';

  try {
    await axios.get(url).then(async res => {
      
      const sessionKey = res.data.session_key;

      var pc = await new WXBizDataCrypt(WXPAY_APP_ID, sessionKey)
      var data = await pc.decryptData(encryptedData, iv)
      
      // 做出响应
      response.send(data);
    }).catch(error => {
      console.log('error: ', error);
      next()
    })
  } catch (error) {
    next(error);
  }
}

/**
 * 更新用户手机型号
 */
export const updatePhoneModel = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { userId, phone_model } = request.body;

  // 手机型号
  let post = { phone_model: phone_model };

  try {
    await updateHouse(post, userId);

    response.send({ code: 200, message: '更新用户手机型号成功 ~' });
  } catch (error) {
    
  }
}
